<?php
/**
 * ActiveRecord 容器
 * <pre>
 * // 查找Brand模型主键为24、25的记录，setAttribute将name字段设置为newName<br>
 * // save方法保存所有model
 * CActiveRecordList::getInstanceByIds('Brand', array(24, 25))
 *  ->setAttribute('name', 'newName')
 *  ->save();
 * 
 * // isActive是一个scope，查出所有is_active为1的model，setAttribute将字段<br>
 * // 设置为0，save方法保存所有model
 * CActiveRecordList::getInstanceByData(Brand::model()->isActive()->findAll())
 *  ->setAttribute('is_active', 0)
 *  ->save();
 * </pre>
 * @author yangdongqi <yangdongqi@hayzone.com>
 * @package lib.collections
 */
class CActiveRecordList extends CTypedList {
	
	/**
	 * __construct
	 * @param array $data
	 * @return void
	 */
	public function __construct($data = null) {
		parent::__construct('CActiveRecord');
		if(is_array($data)) {
			$this->copyFrom($data);
		} elseif(is_object($data)) {
			$this->add($data);
		}
	}
	
	/**
	 * 从已有数据创建实例
	 * @param array $data
	 * @return CActiveRecordList
	 */
	public static function getInstanceByData($data) {
		return new self($data);
	}
	
	/**
	 * 按attributes查找，创建实例 
	 * @param string $modelName
	 * @param array $attributes
	 * @return CActiveRecordList
	 */
	public static function getInstanceByAttributes($modelName, $attributes) {
		$model = new $modelName;
		return new self($modelName, $model->findAllByAttributes($attributes));
	}
	
	/**
	 * 按照给定的primary key(s)，创建实例
	 * @param string $modelName
	 * @param mixed $pks
	 * @return CActiveRecordList
	 */
	public static function getInstanceByPks($modelName, $pks) {
		$criteria = new CDbCriteria();
		$model = new $modelName;
		$pkName = $model->getTableSchema()->primaryKey;
		$pks = is_array($pks) ? $pks : array($pks);
		$criteria->addInCondition($pkName, $pks);
		return new self($model->findAll($criteria));
	}
	
	/**
	 * 设置所有model的attribute
	 * @param string $name
	 * @param mixed $value
	 * @return CActiveRecordList
	 */
	public function setAttribute($name, $value) {
		foreach($this->getIterator() as $one) {
			$one->setAttribute($name, $value);
		}
		return $this;
	}
	
	/**
	 * 设置所有model的attributes
	 * @param array $values
	 * @param boolean $safeOnly
	 * @return CActiveRecordList
	 */
	public function setAttributes($values, $safeOnly = true) {
		foreach($this->getIterator() as $one) {
			$one->setAttributes($values, $safeOnly);
		}
		return $this;
	}
	
	/**
	 * 保存所有model
	 * @param boolean $runValidation
	 * @param mixed $attributes
	 * @return boolean
	 */
	public function save($runValidation = true, $attributes = null) {
		$isSuccess = true;
		foreach($this->getIterator() as $model) {
			$isSuccess &= $model->save($runValidation, $attributes);
		}
		return $isSuccess;
	}
	
	/**
	 * 删除所有model
	 * @return boolean
	 */
	public function delete() {
		$isSuccess = true;
		foreach($this->getIterator() as $index => $model) {
			$result = $model->delete();
			$isSuccess &= $result;
			if($result)
				$this->removeAt($index);
		}
		return $isSuccess;
	}

}

?>